<?php

class NewItemTable extends Doctrine_Table
{

	static public function getLuceneIndex()
	{
	  ProjectConfiguration::registerZend();

	  if (file_exists($index = self::getLuceneIndexFile()))
	  {
	    return Zend_Search_Lucene::open($index);
	  }

	  return Zend_Search_Lucene::create($index);
	}

	static public function getLuceneIndexFile()
	{
		//sfConfig::get('sf_environment')
	  return sfConfig::get('sf_data_dir').'/se_indexes/newitem.index/index';
	}

	static function getStructureNewsQuery()
	{
		return Doctrine::getTable('Structure')->createQuery('b')
			->select('s.*,sng.*,ng.*, ni.*')
			->from('Structure s')
			->innerJoin('s.StructureNewsGroup sng')
			->innerJoin('sng.NewsGroup ng')
			->innerJoin('ng.GroupNews ni')
			->orderBy('s.pri, ni.pri');
	}

	static function getStructureNewsByIdQuery($node){
		$q = self::getStructureNewsQuery();

		if($node && isset($node['id'])){
			$q->andWhere($q->getRootAlias().'.id = ?', $node['id']);
		}

		return $q;
	}

	static function normalizeAssociatedNews(Doctrine_Query $q)
	{
		$result = array();

		$c = 0;
		foreach($q->execute() as $node){
			$result[$c]['node'] = $node;//->toArray();
			$result[$c]['news'] = array();

			if(isset($node['StructureNewsGroup'])){
				foreach($node['StructureNewsGroup'] as $sng){
					if(isset($sng['NewsGroup']) && isset($sng['NewsGroup']['GroupNews'])){
						foreach($sng['NewsGroup']['GroupNews'] as $new){
							$result[$c]['news'][] = $new;//->toArray();
						}
					}
				}
			}
			++$c;
		}

		return $result;
		
	}


	/*
	 * main constraints for frontend modules
	 *
	 */
	static function commonActivityConstraints(Doctrine_Query $q){
		if($q->hasAliasDeclaration('ni') || $q->getRootAlias() == 'ni'){
			$q->andWhere('ni.active_start <= NOW() AND (ni.active_end >= NOW() OR ni.active_end IS NULL)');
		}
		
		return $q;
	}

}